import jaco.mp3.player.MP3Player;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

public class Yang  {
    static String path= Yang.class.getClassLoader().getResource("").getPath();

    static File music = new File(path + "背景音乐.mp3");
    static MP3Player mp3Player = new MP3Player(music);
    static  ArrayList<JButton> though;
    static ArrayList<JButton> cards;
    static int count;
    static int star;

    public Yang(int dff) {
        JFrame frame=new JFrame("羊了个羊");
        though=new ArrayList<>();
        JMenuBar jMenuBar=new JMenuBar();
        mp3Player.play();
        count=0;
        star=1;
        Action replayAction=new AbstractAction("重新游戏") {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Yang(2);
                frame.dispose();
            }
        };
        JMenuItem rePlay=new JMenuItem(replayAction);
        Action easy=new AbstractAction("简单") {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Yang(1);
                frame.dispose();
            }
        };
        Action mid=new AbstractAction("中等（默认）") {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Yang(2);
                frame.dispose();

            }
        };
        Action high=new AbstractAction("困难") {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Yang(3);
                frame.dispose();
            }
        };
        JMenuItem easyItem=new JMenuItem(easy);
        JMenuItem midItem=new JMenuItem(mid);
        JMenuItem highItem=new JMenuItem(high);
        JMenu chose=new JMenu("选择难度");
        chose.add(easyItem);
        chose.add(midItem);
        chose.add(highItem);
        jMenuBar.add(chose);
        jMenuBar.add(rePlay);
        frame.setJMenuBar(jMenuBar);
        JPanel panel=new JPanel();
        panel.setLayout(null);
        JLabel bg=new JLabel(new ImageIcon(path+"背景.jpg"));
        bg.setSize(480,800);
        bg.setLocation(0,0);
        panel.add(bg);

        JToggleButton musicPlay=new JToggleButton();
        musicPlay.setIcon(new ImageIcon(path+"停止音乐.png"));
        musicPlay.setSize(150,80);
        musicPlay.setLocation(330,5);
        musicPlay.setSelectedIcon(new ImageIcon(path+"播放音乐.png"));
        musicPlay.setBorderPainted(false);
        musicPlay.setContentAreaFilled(false);
        musicPlay.addChangeListener(e -> {
            JToggleButton source = (JToggleButton) e.getSource();
            if (source.isSelected()){
                mp3Player.stop();
            }else {
                mp3Player.play();
            }
        });

        panel.add(musicPlay,0);

        if (dff==1){
            cards=creatCards(3);
            Collections.shuffle(cards);
            deal(panel,0,5,5,90,166);
        }else if (dff==2){
            cards=creatCards(6);
            Collections.shuffle(cards);
            deal(panel,0,7,7,30,100);
            deal(panel,49,6,6,60,133);
            deal(panel,49+36,5,5,90,166);
            deal(panel,49+36+25,4,4,120,199);
        }else if (dff==3){
            cards=creatCards(15);
            Collections.shuffle(cards);
            for (int i=0;i<=25*15;i+=49){
                deal(panel,0+i,7,7,30,100);
            }

        }

        check();
        addAction(frame);

        JButton zb=new JButton(new ImageIcon(path+"作弊.png"));
        zb.setLocation(0,0);
        zb.setSize(80,80);
        zb.setBorderPainted(false);
        zb.setContentAreaFilled(false);
        panel.add(zb,0);
        zb.addActionListener(e -> {
            JButton source = (JButton) e.getSource();
            JPanel parent = (JPanel) source.getParent();
            if (though.size()>0&&star<5){
                parent.remove(though.remove(though.size()-1));
                parent.repaint();
            }
            if (star==5){
                JOptionPane.showConfirmDialog(zb,"你现在作弊星级为"+star+"颗星，五星好市民失去游戏资格","羊了个羊",JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE,new ImageIcon(path+"作弊.png"));
                System.exit(0);
            }

            if (though.size()<1){
                JOptionPane.showConfirmDialog(zb,"你现在作弊星级为"+star+"颗星，你现在仅有"+(5-star)+"次作弊机会！","羊了个羊",JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE,new ImageIcon(path+"作弊.png"));
                star++;
            }

        });

        frame.add(panel);
        frame.setSize(495,835);
        frame.setIconImage(new ImageIcon(path+"羊.jpg").getImage());
        frame.setLocationRelativeTo(null);
        frame.setAlwaysOnTop(true);
        frame.setDefaultCloseOperation(3);
        frame.setVisible(true);


    }

    private static void addAction(JFrame frame) {
        for (int i = 0; i < cards.size(); i++) {
            JButton card=cards.get(i);
            card.addActionListener(e -> {
                JButton selected = (JButton) e.getSource();
                if (though.size()==6){
                    int op = JOptionPane.showConfirmDialog(selected, "你输了！是否重新游戏？", "羊了个羊", JOptionPane.YES_NO_OPTION,
                            JOptionPane.INFORMATION_MESSAGE, new ImageIcon(path + "羊.jpg"));
                    if (op==JOptionPane.YES_OPTION){
                        new Yang(2);
                        frame.dispose();

                        return;
                    }else if (op==JOptionPane.NO_OPTION){
                        System.exit(0);
                    }
                }

                cards.remove(selected);
                count--;
                if (count==0){
                    JOptionPane.showConfirmDialog(selected,"你赢了！","羊了个羊",JOptionPane.DEFAULT_OPTION,
                            JOptionPane.INFORMATION_MESSAGE,new ImageIcon(path+"win.png"));
                    return;
                }
                ActionListener actionListener = selected.getActionListeners()[0];
                selected.removeActionListener(actionListener);
                selected.setLocation(20+though.size()*63,642);
                check();
                update(selected);
            });
        }
    }

    private static void update( JButton selected) {
        int found=-1;
        for (int i = 0; i < though.size(); i++) {
            JButton card=though.get(i);
            if (card.getName().equals(selected.getName())){
                though.add(i,selected);
                found=i;
                break;
            }

        }
        if (found==-1){
            though.add(selected);
        }
        if (found!=-1){
            if (though.size()-found>=3){
                JButton jButton = though.get(found + 2);
                if (selected.getName().equals(jButton.getName())){
                    JPanel parent = (JPanel) selected.getParent();
                    parent.remove(though.remove(found));
                    parent.remove(though.remove(found));
                    parent.remove(though.remove(found));
                    parent.repaint();

                }
            }

        }
        for (int i = 0; i < though.size(); i++) {
            JButton jButton = though.get(i);
            int x=25+62*i;
            int y=642;
            jButton.setLocation(x,y);
        }
    }

    private static void check() {
        for (int i = 0; i < cards.size(); i++) {
            JButton card1=cards.get(i);
            card1.setEnabled(true);
            for (int j = i+1; j < cards.size(); j++) {
                JButton card2=cards.get(j);
                int x1=card1.getX()-59;
                int x2=card1.getX()+59;
                int y1=card1.getY()-66;
                int y2=card1.getY()+66;
                if ((card2.getX()>x1&&card2.getX()<x2)&&(card2.getY()>y1&&card2.getY()<y2)){
                    card1.setEnabled(false);
                }
            }
        }
    }

    private static void deal(JPanel panel, int start, int rows, int cols, int x, int y) {
        for (int i = 0; i < rows * cols; i++) {
            if (i+start==cards.size()){
                return;
            }
            int x1=x+i%cols*59;
            int y1=y+i/cols*66;
            JButton card=cards.get(i+start);
            card.setLocation(x1,y1);
            card.setEnabled(false);
            panel.add(card,0);
            count++;
        }
    }

    private static ArrayList<JButton> creatCards(int i) {
        File file=new File("D:\\Javastudy\\Asheep\\res");
        String[] files = file.list();
        String[] names=new String[25];
        int index=0;
        for (String s : files) {
            if (!(s.endsWith("jar")||s.endsWith("mp3")||s.startsWith("羊")||s.startsWith("背景")||s.contains("音乐")||s.contains("win")||(s.contains("作弊")))){
                if (!s.contains("2")){
                    int index1 = s.indexOf(".");

                    names[index]=s.substring(0,index1);
                    index++;
                }
            }
        }
        ArrayList<JButton> newcards=new ArrayList<>();
        for (int i1 = 0; i1 < i; i1++) {
            for (int i2 = 0; i2 < names.length; i2++) {
                String fileName1=path+names[i2]+".png";
                String fileName2=path+names[i2]+"2.png";
                JButton card=new JButton(new ImageIcon(fileName1));
                card.setDisabledIcon(new ImageIcon(fileName2));
                card.setSize(59,66);
                card.setName(names[i2]);
                card.setBorderPainted(false);
                card.setContentAreaFilled(false);
                newcards.add(card);
            }
        }
        return newcards;
    }


}
